package com.hnit.web.controllers;

import com.hnit.exception.InvalidFileTypeException;
import com.hnit.exception.NoFileUploadException;
import com.hnit.service.FileDeduplicationService;
import com.hnit.utils.FileTypeValidator;
import com.hnit.web.Utils.ResponseResult;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController   // restful风格:    请求的method类型: get, post, put, delete,patch     返回值类型:json
@Log
public class FileUploadController {
    @Autowired
    private FileDeduplicationService fileDeduplicationService;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseResult upload(
            @RequestParam("uploadFiles") MultipartFile[] uploadFiles
    ) {
        if (uploadFiles.length == 0) {
            throw new NoFileUploadException("上传文件不能为空");  //抛出文件为空的异常
        }
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : uploadFiles) {
            if (file.isEmpty()) {
                continue;
            }
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();  //文件名
            if (!FileTypeValidator.isValidFileType(contentType, originalFilename)) {
                // 抛出文件类型错误
                throw new InvalidFileTypeException("文件类型不被允许: " + originalFilename + ". 只允许图片、PDF、Word、Excel格式。");
            }
            // Delegate file processing and deduplication to the service
            String fileUrl = fileDeduplicationService.processAndGetFileUrl(file);
            urls.add(fileUrl);
        }
        if (urls.size() > 0) {
            log.info("上传到OSS成功,多个图片的访问地址为:" + urls);
            return ResponseResult.builder().code(1).msg("上传接收数据成功").data(urls).build();
        } else {
            return ResponseResult.builder().code(0).msg("上传文件失败").build();
        }
    }
}